package com.boolib.animate.framework.service.advice;

import com.boolib.animate.commons.Consts;
import com.boolib.animate.commons.exception.UserNameExistException;
import com.boolib.animate.commons.utils.PasswordUtil;
import com.boolib.animate.framework.entity.AnimateUser;
import com.boolib.animate.framework.entity.AnimateWork;
import com.boolib.animate.framework.entity.bo.UserBo;
import com.boolib.animate.framework.entity.bo.UserRegisterBo;
import com.boolib.animate.framework.service.base.impl.BaseAnimateUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author nier
 * @create 2020-03-02 17:44
 */
@Service
public class AnimateUserService {
    @Autowired
    private BaseAnimateUserService baseAnimateUserService;


    public AnimateUser login(UserBo userBo){
        Example example = new Example(AnimateUser.class);
        example.createCriteria().andEqualTo("username",userBo.getUsername())
        .andEqualTo("isDel", Consts.ENABLE)
        .andEqualTo("showStatus",Consts.ENABLE);

        final AnimateUser animateUser = baseAnimateUserService.queryOneByExampleThrow(example);

        PasswordUtil.checkedUserPassword(animateUser.getPassword(),userBo.getPassword(),animateUser.getSalt());

        return animateUser;


    }

    public AnimateUser register(UserRegisterBo userRegisterBo) {
        final AnimateUser animateUser = new AnimateUser();
        animateUser.setUsername(userRegisterBo.getUsername());

        final List<AnimateUser> query = baseAnimateUserService.query(animateUser);

        if(query.size()>0){
            throw new UserNameExistException();
        }

        BeanUtils.copyProperties(userRegisterBo,animateUser);

        animateUser.setSalt(PasswordUtil.getSalt());

        animateUser.setPassword(PasswordUtil.getEncryptPass3(animateUser.getPassword(),animateUser.getSalt()));

        return baseAnimateUserService.saveSelective(animateUser);
    }
}
